package com.citusdata.elven.util;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SystemConfiguration;
import org.apache.log4j.Logger;


public class ConfigManager {
  private static final Logger logger = Logger.getLogger(ConfigManager.class);

  private static CompositeConfiguration config = new CompositeConfiguration();
  private static boolean initialized = false;

  public static synchronized Configuration getConfig() {
    if (!initialized) {
      try {
        config.addConfiguration(new SystemConfiguration());
        config.addConfiguration(new PropertiesConfiguration("http.properties"));
        config.addConfiguration(new PropertiesConfiguration("membership.properties"));
      } catch (ConfigurationException ex) {
        logger.info("Error when loading configuration, using defaults: " + ex);
      }

      initialized = true;
    }
    
    return config;
  }

  public static Configuration getPropertiesConfig(String configName) {
    // This method provides an independent configuration object for components
    // that rely on configuration files for correct initialization.
    Configuration config = null;

    try {
      config = new PropertiesConfiguration(configName);
    } catch (ConfigurationException ex) {
      logger.error("Error when loading configuration", ex);
    }

    return config; 
  }
}
